import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:number_pagination/number_pagination.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:wallpaper_app/api/wallhaven.dart';
import 'package:wallpaper_app/components/Images/image_list_base.dart';
import 'package:wallpaper_app/components/SideBar/tabbar_nav_tap.dart';
import 'package:wallpaper_app/components/input/normal_input.dart';
import 'package:wallpaper_app/model/image_base.dart';
import 'package:wallpaper_app/pages/images/wallhaven/filter_btn.dart';
import 'package:wallpaper_app/pages/images/wallhaven/filter_items.dart';

class WallhavenPage extends StatefulWidget {
  const WallhavenPage({super.key});

  @override
  State<WallhavenPage> createState() => _WallhavenPageState();
}

class _WallhavenPageState extends State<WallhavenPage>
    with TickerProviderStateMixin {
  int page = 1;
  int totalPage = 1;
  List imageList = [];
  bool isLoading = false;
  late TabController tabController;
  TextEditingController textEditingController = TextEditingController();
  TextEditingController ratioController = TextEditingController();
  String apiKey = '';
  String ratio = ''; // 16x9
  String order = 'desc'; // desc or asc
  String categories = '111';
  String purity = '100';
  String customize = '110';
  String ratioSelected = '';
  List types = [
    ['date_added', '最新'],
    ['hot', '热门'],
    ['random', '随机'],
    ['views', '浏览'],
    ['favorites', '收藏'],
    ['toplist', '排行榜'],
  ];
  List<String> subList = [];

  bool isFilterExpanded = false; // 新增筛选器展开/折叠状态

  void getWallhaven() async {
    if (!mounted) return;
    setState(() {
      isLoading = true;
      imageList.clear();
    });
    try {
      Response res = await wallhavenSearch(
        q: textEditingController.text,
        page: page,
        type: types[tabController.index][0],
        apikey: apiKey,
        ratio: ratio,
        order: order,
        purity: purity,
        categories: categories,
      );

      setState(() {
        List imgs = res.data['data'];
        imageList = imgs
            .map(
              (e) => ImageBase(
                largePath: e['path'],
                smallPath: e['thumbs']['original'],
                tags: '',
                width: e['dimension_x'] ?? 1,
                height: e['dimension_y'] ?? 1,
              ),
            )
            .toList();
        totalPage = res.data['meta']['last_page'];
      });
    } catch (e) {
      print(e);
    } finally {
      setState(() {
        isLoading = false;
      });
    }
  }

  void changeOrder(String value) {
    setState(() {
      order = value;
    });
  }

  void changeRatioSelected(value) {
    if (value != null) {
      setState(() {
        ratioSelected = value;
        if (value == 'customize') {
          ratio = ratioController.text;
        } else {
          ratio = value;
        }
      });
    }
  }

  void changeCategories(value) {
    setState(() {
      categories = value;
    });
  }

  void changePurity(value) {
    setState(() {
      purity = value;
    });
  }

  void conditionalQuery() {
    setState(() {
      isFilterExpanded = false;
      page = 1;
      imageList.clear();
    });
    getWallhaven();
  }

  @override
  void initState() {
    for (var i = 0; i < types.length; i++) {
      subList.add(types[i][1]);
    }
    super.initState();
    tabController = TabController(length: subList.length, vsync: this);
    // 获取本地存储的apikey
    SharedPreferences.getInstance().then((prefs) {
      final apikey = prefs.getString('wallhaven_apikey');
      if (apikey != null) {
        apiKey = apikey;
      }
      getWallhaven();
    });
  }

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context).colorScheme;
    return Scaffold(
      body: Stack(
        children: [
          buildImageBody(),
          buildSearchBar(),
          Positioned(
            bottom: 10,
            left: 0,
            right: 0,
            child: NumberPagination(
              onPageChanged: (int pageNumber) {
                setState(() {
                  page = pageNumber;
                });
                getWallhaven();
              },
              visiblePagesCount: 10,
              totalPages: totalPage,
              currentPage: page,
              buttonRadius: 5,
              controlButtonSize: Size(28, 28),
              numberButtonSize: Size(28, 28),
              selectedButtonColor: theme.primary,
            ),
          )
        ],
      ),
    );
  }

  Widget buildSearchBar() {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
      child: Column(
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              TabbarNavTap(
                subList: subList,
                tabController: tabController,
                onTap: (i) {
                  conditionalQuery();
                },
              ),
              Expanded(
                child: NormalInput(
                  controller: textEditingController,
                  height: 35,
                  radius: 5,
                  onSubmitted: (text) {
                    conditionalQuery();
                  },
                ),
              ),
              FilterBtn(
                isFilterExpanded: isFilterExpanded,
                onTap: () {
                  setState(() {
                    isFilterExpanded = !isFilterExpanded;
                  });
                },
              ),
            ],
          ),
          AnimatedSize(
            duration: const Duration(milliseconds: 300),
            curve: Curves.easeInOut,
            child: isFilterExpanded
                ? FilterItems(
                    order: order,
                    ratioSelected: ratioSelected,
                    ratioController: ratioController,
                    categories: categories,
                    purity: purity,
                    changeOrder: changeOrder,
                    changeRatioSelected: changeRatioSelected,
                    changeCategories: changeCategories,
                    changePurity: changePurity,
                    conditionalQuery: conditionalQuery,
                  )
                : const SizedBox.shrink(),
          ),
        ],
      ),
    );
  }

  Widget buildImageBody() {
    return ImageListBase(
      imageList: imageList,
      isLoading: isLoading,
      top: 40,
      isWaterfallFlow: true,
    );
  }

  Widget radioItem({
    required String value,
    required String label,
    required String groupValue,
    required ValueChanged<String> onChanged,
  }) {
    return Row(
      children: [
        Radio<String>(
          value: value,
          groupValue: groupValue,
          onChanged: (value) {
            if (value != null) onChanged(value);
          },
        ),
        Text(label),
      ],
    );
  }
}
